package com.example.dangerouscargodriver.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baiju.netmanager.Http.IHttpRequest;
import com.baiju.style.citylist.Toast.ToastUtils;
import com.example.dangerouscargodriver.R;
import com.example.dangerouscargodriver.controller.AuthController;
import com.example.dangerouscargodriver.entry.MatchLineInfo;
import com.example.dangerouscargodriver.entry.PublishInfo;
import com.example.dangerouscargodriver.module.ResponseInfo;
import com.example.dangerouscargodriver.param.RemoteAPI;
import com.example.dangerouscargodriver.param.RemoteAPICmd;
import com.example.dangerouscargodriver.utils.AppManager;
import com.example.dangerouscargodriver.widget.ActionBar;
import com.example.dangerouscargodriver.widget.MatchLineInfoView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class PublishResourceSuccessActivity extends HttpRequestActivity implements View.OnClickListener {

    private static final String TAG = "PublishResource3";
    private ActionBar mActionBar = null;
    private PublishInfo mPublishInfo = null;
    private List<MatchLineInfo> mMatchLineInfo = null;

    private LinearLayout mLayoutContent = null;
    private TextView mNotPushMsg = null;
    private TextView mPushMsg = null;
    private LinearLayout mPushLayout = null;
    private List<Integer> mSelectList = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.initHttpComponent(PublishResourceSuccessActivity.class);
        setContentView(R.layout.activity_publish_resource_success);
        mSelectList = new ArrayList<>();

        Intent intent = getIntent();
        if(intent != null && intent.getSerializableExtra("info") != null){
            mPublishInfo = (PublishInfo) intent.getSerializableExtra("info");
        }

        if(mPublishInfo != null) {
            executeGetMatchLineInfo();
        }

        mLayoutContent = findViewById(R.id.layout_content);
        mNotPushMsg = findViewById(R.id.btn_not_push_resource_info);
        mNotPushMsg.setOnClickListener(this);
        mPushLayout = findViewById(R.id.layout_push_message);
        mPushMsg = findViewById(R.id.btn_push_resource_info);
        mPushMsg.setOnClickListener(this);

        mActionBar = findViewById(R.id.actionBarPublicResourceStepThree);
        mActionBar.setOnBackClickListener( new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                AppManager.getAppManager().finishActivity();
                AppManager.getAppManager().finishActivity();
                finish();
            }
        });
    }

    private void executeGetMatchLineInfo() {
        HashMap<String, String> header = new HashMap<>();
        header.put("token", AuthController.Instance().getToken());

        HashMap<String, String> param = new HashMap<>();
        param.put("id", mPublishInfo.getRecid());

        sendHttpRequest(IHttpRequest.RequestMethod.GET_METHOD,
                RemoteAPI.REQUEST_V1_SG_TERMINATE_SG,
                header,
                param,
                RemoteAPICmd.REQUEST_V1_SG_TERMINATE_SG);
    }

    private void executePushMsgInfo() {
        HashMap<String, String> header = new HashMap<>();
        header.put("token", AuthController.Instance().getToken());

        HashMap<String, String> param = new HashMap<>();
        param.put("sg_id", mPublishInfo.getRecid());
        String sr_id = "";
        for(int index = 0; index < mSelectList.size(); index++){
            sr_id += mMatchLineInfo.get(mSelectList.get(index)).getId();
            sr_id += ",";
        }
        if(sr_id.length() > 0){
            sr_id = sr_id.substring(0, sr_id.length() - 1);
            param.put("sr_id", sr_id);
        }

        sendHttpRequest(IHttpRequest.RequestMethod.POST_METHOD,
                RemoteAPI.REQUEST_V2_SG_INVITE_SR,
                header,
                param,
                RemoteAPICmd.REQUEST_V2_SG_INVITE_SR);
    }

    private void refreshMatchLineInfoView(){
        if(mMatchLineInfo != null && mMatchLineInfo.size() > 0){
            mPushLayout.setVisibility(View.VISIBLE);
            mLayoutContent.removeAllViews();
            for(int index = 0; index < mMatchLineInfo.size(); index++){
                final int select = index;
                MatchLineInfoView item = new MatchLineInfoView(this, mMatchLineInfo.get(index));
                item.addCheckedListener(new MatchLineInfoView.onCheckListener() {
                    @Override
                    public void onChecked() {
                        for(int index = 0; index < mSelectList.size(); index++){
                            if(mSelectList.get(index) == select){
                                return;
                            }
                        }
                        mSelectList.add(select);
                    }

                    @Override
                    public void onUnChecked() {
                        for(int index = 0; index < mSelectList.size(); index++){
                            if(mSelectList.get(index) == select){
                                mSelectList.remove(index);
                                return;
                            }
                        }
                    }
                });
                mLayoutContent.addView(item);
            }
        }
        else{

        }
    }

    @Override
    protected void onHttpResponse(int actionId, String response) {
        try {
            JSONObject res = new JSONObject(response);
            Gson gson = new Gson();
            if(actionId == RemoteAPICmd.REQUEST_V1_SG_TERMINATE_SG){
                Log.d(TAG, "onResponse: " + response);
                ResponseInfo responseInfo = gson.fromJson(response, ResponseInfo.class);
                if(responseInfo != null && responseInfo.getStatus() == 1){
                    JSONObject data = res.getJSONObject("data");
                    if(data != null) {
                        Type type = new TypeToken<List<MatchLineInfo>>() {}.getType();
                        mMatchLineInfo = gson.fromJson(data.get("route").toString(), type);
                        refreshMatchLineInfoView();
                    }
                }
            }
            else if(actionId == RemoteAPICmd.REQUEST_V2_SG_INVITE_SR){
                Log.d(TAG, "onResponse: " + response);
                ResponseInfo responseInfo = gson.fromJson(response, ResponseInfo.class);
                if(responseInfo != null && responseInfo.getStatus() == 1){
                    ToastUtils.showLongToast(this, "推送成功");
                }
                else{
                    ToastUtils.showLongToast(this, "推送失败");
                }
            }
            else{

            }
        }
        catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onHttpErrorResponse(int actionId, String response) {
        if(actionId == RemoteAPICmd.REQUEST_V2_SG_INVITE_SR){
            ToastUtils.showLongToast(this, "推送失败");
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            AppManager.getAppManager().finishActivity();
            AppManager.getAppManager().finishActivity();
            finish();
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.btn_not_push_resource_info){
            AppManager.getAppManager().finishActivity();
            AppManager.getAppManager().finishActivity();
            finish();
        }
        else if(v.getId() == R.id.btn_push_resource_info){
            executePushMsgInfo();
        }
        else{

        }
    }
}